package com.hifar.test.api.controller;

import com.hifar.test.api.constant.AuthConstants;
import com.hifar.test.api.model.*;
import com.hifar.test.api.service.DataReceiverService;
import com.hifar.test.api.util.AuthUtil;
import com.hifar.test.api.util.RSAUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 数据接收端控制器
 * 作为数据资产管理平台，接收外部系统发送的数据
 *
 * @author system
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api/busi/test/api/data-receiver")
@Api(tags = "数据接收端接口")
public class DataReceiverController {

    private static final Logger logger = LoggerFactory.getLogger(DataReceiverController.class);

    @Autowired
    private DataReceiverService dataReceiverService;

    /**
     * 接收组织信息数据
     *
     * @param dataRequest 数据请求
     * @param request HTTP请求对象
     * @return 响应结果
     */
    @PostMapping("/organization")
    @ApiOperation("接收组织信息数据")
    public DataResponse receiveOrganizationData(
            @RequestBody DataRequest dataRequest,
            HttpServletRequest request) {

        logger.info("=== 进入DataReceiverController.receiveOrganizationData方法 ===");
        String clientIp = getClientIpAddress(request);
        logger.info("接收到组织信息数据请求，客户端IP: {}, 模型代码: {}",
                clientIp, dataRequest.getModelCode());

        try {
            // 检查认证
            String authError = checkAuthentication(request);
            if (authError != null) {
                return createAuthFailureDataResponse(authError, dataRequest, "organization");
            }

            // 验证请求数据
            if (!validateDataRequest(dataRequest)) {
                return createValidationFailureDataResponse("数据格式验证失败");
            }

            // 处理数据
            DataResponse response = dataReceiverService.processOrganizationData(dataRequest, clientIp);

            logger.info("组织信息数据处理完成，状态: {}, 消息: {}",
                    response.getStatus(), response.getMessage());

            return response;

        } catch (Exception e) {
            logger.error("处理组织信息数据异常", e);
            return createSystemFailureDataResponse("服务器内部错误: " + e.getMessage());
        }
    }

    /**
     * 接收员工数据
     *
     * @param dataRequest 数据请求
     * @param request HTTP请求对象
     * @return 响应结果
     */
    @PostMapping("/employee")
    @ApiOperation("接收员工数据")
    public DataResponse receiveEmployeeData(
            @RequestBody DataRequest dataRequest,
            HttpServletRequest request) {

        String clientIp = getClientIpAddress(request);
        logger.info("接收到员工数据请求，客户端IP: {}, 模型代码: {}",
                clientIp, dataRequest.getModelCode());

        try {
            // 检查认证
            String authError = checkAuthentication(request);
            if (authError != null) {
                return createAuthFailureDataResponse(authError, dataRequest, "employee");
            }

            // 验证请求数据
            if (!validateDataRequest(dataRequest)) {
                return createValidationFailureDataResponse("数据格式验证失败");
            }

            // 处理数据
            DataResponse response = dataReceiverService.processEmployeeData(dataRequest, clientIp);

            logger.info("员工数据处理完成，状态: {}, 消息: {}",
                    response.getStatus(), response.getMessage());

            return response;

        } catch (Exception e) {
            logger.error("处理员工数据异常", e);
            return createSystemFailureDataResponse("服务器内部错误: " + e.getMessage());
        }
    }
    /**
     * 验证数据请求
     *
     * @param dataRequest 数据请求
     * @return 是否有效
     */
    private boolean validateDataRequest(DataRequest dataRequest) {
        if (dataRequest == null) {
            logger.warn("数据请求为空");
            return false;
        }

        if (dataRequest.getModelCode() == null || dataRequest.getModelCode().trim().isEmpty()) {
            logger.warn("模型代码为空");
            return false;
        }

        if (dataRequest.getDataStatus() == null) {
            logger.warn("数据状态为空");
            return false;
        }

        if (dataRequest.getData() == null || dataRequest.getData().isEmpty()) {
            logger.warn("数据列表为空");
            return false;
        }

        return true;
    }

    /**
     * 获取客户端IP地址
     *
     * @param request HTTP请求对象
     * @return 客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        return request.getRemoteAddr();
    }

    /**
     * 检查认证
     *
     * @param request HTTP请求对象
     * @return 认证错误信息，如果认证成功返回null
     */
    private String checkAuthentication(HttpServletRequest request) {
        try {
            // 获取Authorization头
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null) {
                return "认证失败：缺少Authorization头";
            }

            // 检查Basic认证格式
            if (!authHeader.startsWith("Basic ")) {
                return "认证失败：认证头格式错误";
            }

            // 提取凭据
            String credentials = AuthUtil.extractCredentials(authHeader);
            if (credentials == null || credentials.trim().isEmpty()) {
                return "认证失败：凭据为空";
            }

            // 解析用户名和密码
            String[] parts = credentials.split(":", 2);
            if (parts.length != 2) {
                return "认证失败：凭据格式错误";
            }

            String username = parts[0];
            String encryptedPassword = parts[1];

            if (username == null || username.trim().isEmpty()) {
                return "认证失败：用户名为空";
            }

            if (encryptedPassword == null || encryptedPassword.trim().isEmpty()) {
                return "认证失败：密码为空";
            }

            // 验证用户名
            if (!AuthConstants.DEFAULT_USERNAME.equals(username)) {
                return "认证失败：用户名错误";
            }

            // 使用RSA私钥解密密码
            String decryptedPassword;
            try {
                decryptedPassword = RSAUtil.decryptPassword(encryptedPassword);
            } catch (Exception e) {
                logger.error("密码解密失败", e);
                return "认证失败：密码解密错误";
            }

            // 验证解密后的密码
            if (!AuthConstants.DEFAULT_PASSWORD.equals(decryptedPassword)) {
                return "认证失败：密码错误";
            }

            return null; // 认证成功

        } catch (Exception e) {
            logger.error("认证检查异常", e);
            return "认证失败：系统错误";
        }
    }

    /**
     * 创建认证失败响应（DataResponse格式）
     *
     * @param authError 认证错误信息
     * @param dataRequest 数据请求
     * @param dataType 数据类型（organization/employee）
     * @return 认证失败响应
     */
    private DataResponse createAuthFailureDataResponse(String authError, DataRequest dataRequest, String dataType) {
        try {
            // 创建失败数据列表
            java.util.List<com.hifar.test.api.model.FailedData> failedDataList = new java.util.ArrayList<>();

            if (dataRequest != null && dataRequest.getData() != null) {
                for (int i = 0; i < dataRequest.getData().size(); i++) {
                    String taskId;
                    List<DataBusinessData> dataBusinessDataList = dataRequest.getData();
                    Assert.notNull(dataBusinessDataList,"data数据为空!");
                    DataBusinessData dataBusinessData = dataBusinessDataList.get(i);
                    Assert.notNull(dataBusinessData,"dataBusinessData数据为空!");
                    DataItem businessData = dataBusinessData.getBusinessData();
                    Assert.notNull(businessData,"businessData数据为空!");
                    if ("organization".equals(dataType)) {
                        // 组织数据使用部门ID
                        taskId = businessData.getOrganizationInfo() != null ?
                            businessData.getOrganizationInfo().getId() : "ORG_" + i;
                    } else {
                        // 员工数据使用用户ID
                        taskId = businessData.getEmployee() != null ?
                            businessData.getEmployee().getUserCode() : "USER_" + i;
                    }

                    com.hifar.test.api.model.FailedData failedData = new com.hifar.test.api.model.FailedData(
                            taskId, "failure", authError);
                    failedDataList.add(failedData);
                }
            } else {
                // 如果没有数据，创建一个默认的失败项
                com.hifar.test.api.model.FailedData failedData = new com.hifar.test.api.model.FailedData(
                        "AUTH_ERROR", "failure", authError);
                failedDataList.add(failedData);
            }

            // 创建DataResponse格式的响应
            DataResponse response = new DataResponse();
            response.setStatus(-1);
            response.setMessage(authError);

            ResponseData responseData = new ResponseData();
            responseData.setSuccessCount(0);
            responseData.setFailedData(failedDataList);
            response.setData(responseData);

            return response;

        } catch (Exception e) {
            logger.error("创建认证失败响应异常", e);
            return createSystemFailureDataResponse("认证失败：系统错误");
        }
    }

    /**
     * 创建验证失败响应（DataResponse格式）
     *
     * @param message 错误消息
     * @return 验证失败响应
     */
    private DataResponse createValidationFailureDataResponse(String message) {
        DataResponse response = new DataResponse();
        response.setStatus(-1);
        response.setMessage(message);

        ResponseData responseData = new ResponseData();
        responseData.setSuccessCount(0);
        responseData.setFailedData(new java.util.ArrayList<>());
        response.setData(responseData);

        return response;
    }

    /**
     * 创建系统失败响应（DataResponse格式）
     *
     * @param message 错误消息
     * @return 系统失败响应
     */
    private DataResponse createSystemFailureDataResponse(String message) {
        DataResponse response = new DataResponse();
        response.setStatus(-1);
        response.setMessage(message);

        ResponseData responseData = new ResponseData();
        responseData.setSuccessCount(0);

        java.util.List<com.hifar.test.api.model.FailedData> failedDataList = new java.util.ArrayList<>();
        com.hifar.test.api.model.FailedData failedData = new com.hifar.test.api.model.FailedData(
                java.util.UUID.randomUUID().toString(), "failure", message);
        failedDataList.add(failedData);
        responseData.setFailedData(failedDataList);
        response.setData(responseData);

        return response;
    }
}
